from surprise import SVDpp, NormalPredictor

from AnimeListLoader import AnimeListLoader
from Evaluator import Evaluator


def process_rating_csv():
    # 预处理数据集
    import pandas as pd

    # 加载原始数据
    file_path = './datasets/my-anime-list/reviews.csv'
    reviews = pd.read_csv(file_path)

    # 过滤掉以 '-' 开头的 profile
    # reviews = reviews[~reviews['profile'].str.startswith('-')]

    # 为 profile 分配唯一 ID
    profile_to_id = {profile: idx + 1 for idx, profile in enumerate(reviews['profile'].unique())}
    reviews['profile_id'] = reviews['profile'].map(profile_to_id)

    # 查看结果
    print(reviews[['profile', 'profile_id']].head())

    # 只保留必要列
    reviews = reviews[['profile_id', 'anime_uid', 'score']]

    # 保存为新的 CSV 文件
    reviews.to_csv('./datasets/my-anime-list/reviews_processed.csv', index=False)


def LoadData():
    loader = AnimeListLoader(max_rows=2000)
    print("Loading movie ratings...")
    data = loader.load_dataset()
    print("\nComputing movie popularity ranks so we can measure novelty later...")
    rankings = loader.get_popularity_ranks()

    return (loader, data, rankings)


def test_loader():
    loader = AnimeListLoader()

    loader.load_dataset()

    print(loader.id_to_name)
    print(loader.name_to_id)

    # Gundam Build Fighters Try
    print(loader.get_id("Gundam Build Fighters Try"))
    # 24625
    print(loader.get_name(24625))


def test_model():
    # 获取数据
    loader, data, rankings = LoadData()
    # 创建评估器
    evaluator = Evaluator(data, rankings)
    # 添加算法

    # SVD++ 奇异值分解
    SVDPlusPlus = SVDpp()
    evaluator.AddAlgorithm(SVDPlusPlus, "SVD++")

    # 随机预测
    Random = NormalPredictor()
    evaluator.AddAlgorithm(Random, "Random")

    # 开始训练评估
    evaluator.Evaluate(doTopN=True)

    # 获取topN个推荐数据
    # evaluator.SampleTopNRecs(loader=loader, userID=6, k=10)

    # 测试冷启动(遇到新的用户或物品)
    recommendations = evaluator.SampleTopNRecs(loader=loader, userID=888888888, k=10)
    for ratings in recommendations[:10]:
        # print(ratings)
        print(loader.get_name(ratings[0]), ratings[1])


def show_version():
    import surprise
    print(surprise.__version__)
    import flask
    print(flask.__version__)
    import numpy
    print(numpy.__version__)
    import pandas
    print(pandas.__version__)
    import sklearn
    print(sklearn.__version__)
    import joblib
    print(joblib.__version__)


if __name__ == '__main__':
    # test_loader()
    # test_model()
    show_version()
